<template>
  <div class="hot-tag-list">
    <div class="col-6 col-md-4 col-lg-3 col-xl-2 hot-tag-item" v-for="item in tagsData.data" :key="item._id">
      <a href="" class="tag-item-container">
        <img src="../assets/default.jpg" alt="" lazyload="true" :data-original="item.image">
        <p class="item-name">{{item.name}}</p>
        <p class="item-number">{{item.numbers}}门课程</p>
      </a>
    </div>
  </div>
</template>

<script>
import { onMounted, reactive } from 'vue'
import { getTagList } from '../api'
export default {
  setup () {
    const tagsData = reactive({
      data: []
    })
    onMounted(async () => {
      lazyload()
      const res = await getTagList()
      tagsData.data = res.data
    })
    // 图片懒加载
    function lazyload () {
      const scrollY = document.documentElement.scrollTop
      const offsetHeight = document.documentElement.offsetHeight
      const imgs = document.querySelectorAll('img[data-original][lazyload]')
      imgs.forEach(item => {
        if (item.dataset.original === '') {
          return
        }
        const rect = item.getBoundingClientRect()
        // if (rect.bottom >= 0 && rect.top < scrollY + offsetHeight) {
        const img = new Image()
        img.src = item.dataset.original
        // console.log(img.src)
        img.onload = function() {
          item.src = img.src
        }
        item.removeAttribute('data-original')
        item.removeAttribute('lazyload')
        // }
      })
    }
    document.addEventListener('scroll', lazyload)

    return { tagsData }
  }
}
</script>

<style lang="scss" scoped>
.hot-tag-list {
  border-bottom: 1px solid #f0f0f0;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-wrap: wrap;
  .hot-tag-item {
    border-top: 1px solid #f0f0f0;
    border-left: 1px solid #f0f0f0;
    .tag-item-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 17px 10px 7px;
      img {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        margin-bottom: 10px;
        transition: all 0.4s ease;
        &:hover {
          transform: scale(1.1);
        }
      }
      .item-number {
        color: #15c288 !important;
      }
      .item-name {
        margin-bottom: 0px;
        color: #666 !important;
      }
    }
  }
}
</style>
